package com.ruoyi.project.applet.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.applet.domain.Collect;
import com.ruoyi.project.applet.domain.Good;
import com.ruoyi.project.applet.service.ICollectService;
import com.ruoyi.project.applet.service.impl.GoodServiceImpl;
import com.ruoyi.project.system.domain.SysUserWx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏Controller
 * 
 * @author ruoyi
 * @date 2025-04-28
 */
@RestController
@RequestMapping("/applet/collect")
public class CollectController extends BaseController
{
    @Autowired
    private ICollectService collectService;

    @Autowired
    private GoodServiceImpl goodService;
    /**
     * 查询收藏列表
     */

    @GetMapping("/list")
    public TableDataInfo list(Collect collect)
    {
        LoginUser loginUser = getLoginUser();
        SysUserWx userWx = loginUser.getUserWx();
        Assert.notNull(userWx,"请先登录");
        collect.setUserId(userWx.getOpenId());
        List<Collect> list = collectService.selectCollectList(collect);
        List<String> goodIds = list.stream().map(Collect::getGoodId).collect(Collectors.toList());
        startPage();
        List<Good> goodList = goodService.selectGoodByIds(goodIds);
        return getDataTable(goodList);
    }


    /**
     * 新增收藏
     */

    @PostMapping
    public AjaxResult add(@RequestBody Collect collect)
    {
        LoginUser loginUser = getLoginUser();
        SysUserWx userWx = loginUser.getUserWx();
        Assert.notNull(userWx,"请先登录");
        collect.setUserId(userWx.getOpenId());
        collect.setCreateTime(DateUtils.getNowDate());
        return toAjax(collectService.insertCollect(collect));
    }


    /**
     * 取消收藏
     */

	@DeleteMapping("/{goodId}")
    public AjaxResult remove(@PathVariable String goodId)
    {
        LoginUser loginUser = getLoginUser();
        SysUserWx userWx = loginUser.getUserWx();
        Assert.notNull(userWx,"请先登录");
        Collect collect = new Collect();
        collect.setUserId(userWx.getOpenId());
        collect.setGoodId(goodId);
        return toAjax(collectService.deleteCollect(collect));
    }
}
